export type EncryptionRecord = {
  cipherPath: string;
  cipherName: string;
  sourcePath: string;
  createdAt: string;
  deviceIndex: number;
  deviceLabel: string;
  deviceSN: string;
  certSubject: string;
  certAlgorithm: string;
};

const META_SUFFIX = ".zjcameta.json";

export const getMetaPathByCipher = (cipherPath: string) =>
  cipherPath ? `${cipherPath}${META_SUFFIX}` : "";

const stringifyMeta = (record: EncryptionRecord) =>
  JSON.stringify(record, null, 2);

export const saveEncryptionMeta = (
  zjca: any,
  cipherPath: string,
  record: EncryptionRecord
): { ok: boolean; path: string; message?: string } => {
  if (!zjca || typeof zjca.writeFile !== "function") {
    return { ok: false, path: "", message: "SDK 未提供 writeFile 接口" };
  }
  const metaPath = getMetaPathByCipher(cipherPath);
  if (!metaPath) return { ok: false, path: "", message: "无效的密文路径" };
  try {
    const resp = zjca.writeFile(metaPath, stringifyMeta(record), false);
    if (resp && typeof resp.code === "number" && resp.code !== 0) {
      return { ok: false, path: metaPath, message: resp.msg || `${resp.code}` };
    }
    return { ok: true, path: metaPath };
  } catch (error: any) {
    return { ok: false, path: metaPath, message: error?.message || String(error) };
  }
};

export const readEncryptionMeta = (
  zjca: any,
  cipherPath: string
): EncryptionRecord | null => {
  if (!cipherPath || !zjca || typeof zjca.readFile !== "function") return null;
  const metaPath = getMetaPathByCipher(cipherPath);
  if (!metaPath) return null;
  try {
    const resp = zjca.readFile(metaPath, false);
    if (resp?.code !== 0 || !resp.res) return null;
    return JSON.parse(resp.res);
  } catch (error) {
    console.warn("读取密文元数据失败:", error);
    return null;
  }
};
